package com.p2p.config;

import com.p2p.handler.PeerJsHandshakeInterceptor;
import com.p2p.service.AuthService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import com.p2p.handler.PeerJsWebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * WebSocket配置类
 * 实现FRONTEND_INTERFACE.md中定义的通信协议的WebSocket端点配置
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Resource
    private AuthService authService;
    /**
     * 注册WebSocket处理器
     * 配置文档中定义的WebSocket端点
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

        // 注册带/peerjs后缀的端点，兼容前端测试
        registry.addHandler(new PeerJsWebSocketHandler(authService), "/peerjs")
                .setAllowedOrigins("*"); // 允许所有来源
    }

    // 创建握手拦截器，用于预处理URI
    public HandshakeInterceptor peerJsHandshakeInterceptor() {
        return new PeerJsHandshakeInterceptor();
    }
}
